//
//  YWCirculationDBManager.m
//  maintain
//
//  Created by Kyo on 16/8/31.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWCirculationDBManager.h"
#import "YWDBTool.h"

#import "YWCirculationInfo.h"

@implementation YWCirculationDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}

#pragma mark - 流转信息表
- (BOOL)createCirculationInfoTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'circulationInfo' (infoId integer,troubleId integer,authorId integer,recipientId integer,createTime timestamp,note text,isRead boolean DEFAULT 0,type smallint);";
    return [[self fmdb] executeUpdate:sql];
}

#pragma mark - 增删改查等
- (BOOL)updateCirculationInfoWithArray:(NSArray*)circulationInfoArray{
    if (circulationInfoArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockCirculationInfoArray = circulationInfoArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockCirculationInfoArray enumerateObjectsUsingBlock:^(YWCirculationInfo* _Nonnull circulationInfo, NSUInteger idx, BOOL* _Nonnull stop) {
//            (circulationInfo.type == YWCirculationInfoTypePostTrouble || circulationInfo.type == YWCirculationInfoTypeFinishTroubleMission || circulationInfo.type == YWCirculationInfoTypeAssignTroubleMission) &&
            if (circulationInfo.troubleId!=0 && idx == 0) {
                sql = @"DELETE FROM 'circulationInfo' WHERE troubleId=?;";
                executeResult = [db executeUpdate:sql,@(circulationInfo.troubleId)];
                if (executeResult) {
                    sql = @"INSERT INTO 'circulationInfo' (infoId,troubleId,authorId,recipientId,createTime,note,isRead,type) VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
                    executeResult = [db executeUpdate:sql, @(circulationInfo.infoId),@(circulationInfo.troubleId),@(circulationInfo.author.uniqueId),@(circulationInfo.recipient.uniqueId),@(circulationInfo.createTime),circulationInfo.note,@(circulationInfo.isRead),@(circulationInfo.type)];
                }
                
            }else{
                sql = @"SELECT * FROM 'circulationInfo' WHERE infoId=? AND type=?;";
                FMResultSet* set = [db executeQuery:sql, @(circulationInfo.infoId), @(circulationInfo.type)];
                //没有更新isRead
                if ([set next]) {
                    sql = @"UPDATE 'circulationInfo' SET troubleId=?,authorId=?,recipientId=?,createTime=?,note=? WHERE infoId=? AND type=?;";
                    executeResult = [db executeUpdate:sql, @(circulationInfo.troubleId),@(circulationInfo.author.uniqueId),@(circulationInfo.recipient.uniqueId),@(circulationInfo.createTime),circulationInfo.note, @(circulationInfo.infoId), @(circulationInfo.type)];
                }
                else {
                    sql = @"INSERT INTO 'circulationInfo' (infoId,troubleId,authorId,recipientId,createTime,note,isRead,type) VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
                    executeResult = [db executeUpdate:sql, @(circulationInfo.infoId),@(circulationInfo.troubleId),@(circulationInfo.author.uniqueId),@(circulationInfo.recipient.uniqueId),@(circulationInfo.createTime),circulationInfo.note,@(circulationInfo.isRead),@(circulationInfo.type)];
                }
            }
            
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)saveCirculationInfoWithArray:(NSArray*)circulationInfoArray{
    if (circulationInfoArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockCirculationInfoArray = circulationInfoArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockCirculationInfoArray enumerateObjectsUsingBlock:^(YWCirculationInfo* _Nonnull circulationInfo, NSUInteger idx, BOOL* _Nonnull stop) {
                sql = @"SELECT * FROM 'circulationInfo' WHERE infoId=? AND type=?;";
                FMResultSet* set = [db executeQuery:sql, @(circulationInfo.infoId), @(circulationInfo.type)];
                //没有更新isRead
                if ([set next]) {
                    sql = @"UPDATE 'circulationInfo' SET troubleId=?,authorId=?,recipientId=?,createTime=?,note=? WHERE infoId=? AND type=?;";
                    executeResult = [db executeUpdate:sql, @(circulationInfo.troubleId),@(circulationInfo.author.uniqueId),@(circulationInfo.recipient.uniqueId),@(circulationInfo.createTime),circulationInfo.note, @(circulationInfo.infoId), @(circulationInfo.type)];
                }
                else {
                    sql = @"INSERT INTO 'circulationInfo' (infoId,troubleId,authorId,recipientId,createTime,note,isRead,type) VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
                    executeResult = [db executeUpdate:sql, @(circulationInfo.infoId),@(circulationInfo.troubleId),@(circulationInfo.author.uniqueId),@(circulationInfo.recipient.uniqueId),@(circulationInfo.createTime),circulationInfo.note,@(circulationInfo.isRead),@(circulationInfo.type)];
                }
            
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}


- (BOOL)updateReadStatusWithTroubleId:(NSInteger)troubleId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'circulationInfo' SET isRead=? WHERE troubleId=?;";
        executeResult = [db executeUpdate:sql, @(YES),@(troubleId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (NSInteger)noReadCountWithTroubleId:(NSInteger)troubleId{
    __block NSInteger noReadCount = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* countSql = @"SELECT COUNT(*) AS noReadCount FROM 'circulationInfo' WHERE isRead=0 AND troubleId=?";
        FMResultSet* countSet = [db executeQuery:countSql,@(troubleId)];
        if ([countSet next]) {
            noReadCount = [countSet intForColumn:@"noReadCount"];
        }
        [db closeOpenResultSets];
    }];
    return noReadCount;
}
- (NSArray *)circulationInfoArrayWithTroubleId:(NSInteger)troubleId{
    __block NSMutableArray* circulationInfoArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'circulationInfo' WHERE troubleId=? order by createtime DESC;";//AND infoId>0,新构建的流转infoId是负的
        FMResultSet* set = [db executeQuery:sql, @(troubleId)];
        while ([set next]) {
            YWCirculationInfo* circulationInfo = [self circulationInfoWithFMResultSet:set FMDatabase:db];
            [circulationInfoArray addObject:circulationInfo];
        }
        [db closeOpenResultSets];
    }];
    return circulationInfoArray;
}

- (YWCirculationInfo *)circulationInfoWithCirculationType:(NSInteger)type troubleId:(NSInteger)troubleId{
    __block YWCirculationInfo* circulationInfo = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'circulationInfo' WHERE troubleId=? AND type=? AND infoId>0 order by createtime DESC;";
        FMResultSet* set = [db executeQuery:sql, @(troubleId),@(type)];
        if ([set next]) {
            circulationInfo = [self circulationInfoWithFMResultSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return circulationInfo;
}

- (YWCirculationInfo *)circulationInfoWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWCirculationInfo* circulationInfo = [[YWCirculationInfo alloc] init];
    circulationInfo.infoId = [set intForColumn:@"infoId"];
    circulationInfo.troubleId = [set intForColumn:@"troubleId"];
    NSInteger authorId = [set intForColumn:@"authorId"];
    NSString* authorsql = @"SELECT * FROM 'handler' WHERE uniqueId =?;";
    FMResultSet* authorSet = [db executeQuery:authorsql, @(authorId)];
    if ([authorSet next]) {
        circulationInfo.author = [[YWDBTool shareDBTool] handlerWithSet:authorSet];
    }
    NSInteger recipientId = [set intForColumn:@"recipientId"];
    NSString* recipientsql = @"SELECT * FROM 'handler' WHERE uniqueId =?;";
    FMResultSet* recipientSet = [db executeQuery:recipientsql, @(recipientId)];
    if ([recipientSet next]) {
        circulationInfo.recipient = [[YWDBTool shareDBTool] handlerWithSet:recipientSet];
    }
    circulationInfo.createTime = [set longLongIntForColumn:@"createTime"];
    circulationInfo.note = [set stringForColumn:@"note"];
    circulationInfo.isRead = [set intForColumn:@"isRead"];
    circulationInfo.type = [set intForColumn:@"type"];
    return circulationInfo;
}
@end
